package cn.cs.controller;

import cn.cs.common.*;
import cn.cs.pojo.SetPolicy;
import cn.cs.service.SetPolicyService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping(value = "/setPolicy")
public class SetPolicyController {

    @Resource
    private SetPolicyService setPolicyService;

    /**
     * 分页查询 结算方案
     * @param pageNumber
     * @param pageSize
     * @return
     * @throws Exception
     * TODO 添加搜索
     */
    @RequestMapping(value = "/csPlatform/getSetPolicyByPage")
    public Dto getSetPolicyByPage(Integer pageNumber, Integer pageSize, String polName, String polType)throws Exception{
        Map<String, Object> param = new HashMap<>();
        param.put("polName", polName);
        param.put("polType", polType);
        return DtoUtil.returnSuccess("获取成功", setPolicyService.querySetPolicyPageByMap(param, pageNumber, pageSize));
    }

    /**
     * 新增/编辑 结算方案
     * @param setPolicy
     * @return
     */
    @RequestMapping(value = "/csPlatform/updateSetPolicy")
    public Dto updateSetPolicy(@RequestBody SetPolicy setPolicy){
        try {
            String msg = "新增成功";
            if (EmptyUtils.isEmpty(setPolicy.getId())) {
                Map<String, Object> map = new HashMap<>();
                map.put("polType", setPolicy.getPolType());
                List<SetPolicy> list = setPolicyService.getSetPolicyListByMap(map);
                if(list.size() == 0){
                    setPolicy.setId(IdWorker.getId());
                    setPolicy.setCreateTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                    setPolicyService.addSetPolicy(setPolicy);
                }else{
                    return DtoUtil.returnFail("操作失败，结算方案只允许有一条数据", "002");
                }
            } else {
                setPolicy.setUpdateTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                msg = "修改成功";
                setPolicyService.modifySetPolicy(setPolicy);
            }
            return DtoUtil.returnSuccess(msg);
        }catch (Exception e){
            e.printStackTrace();
            return DtoUtil.returnFail("操作失败，请重试", "001");
        }
    }

    @RequestMapping(value = "/csPlatform/delSetPolicy")
    public Dto delProductType(String ids)throws Exception{
        int i = 0;
        for(String id:ids.split(",")){
            i += setPolicyService.deleteSetPolicyById(Long.valueOf(id));
        }
        if(i>0){
            return DtoUtil.returnSuccess("操作成功", i);
        }else {
            return DtoUtil.returnFail("操作失败，请重试", "001");
        }
    }

}
